package pers.w.chaptertalk.funs.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pers.w.chaptertalk.funs.Fun;

public class Tab_Chapter extends Tab_Base {
    static final String NAME = "chapter";

    public static final String CHAPTERNAME = "chapterName";
    public static final String CHAPTERURI = "chapterUri";
    public static final String CHAPTERUPDATETIME = "chapterUpdateTime";
    static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS " +
            NAME + " ( _id integer," +
            CHAPTER_ID + " integer  primary key autoincrement," +
            CHAPTERNAME + " varchar," +
            CHAPTERURI + " varchar," +
            CHAPTERUPDATETIME + " varchar" +
            ") ";

    Tab_Chapter(SQLiteDatabase db) {
        super(db);
        fields = new String[]{CHAPTERNAME, CHAPTERURI, CHAPTERUPDATETIME};
    }


    public long  add(long book_id, List<Map<String, String>> chapters) {
        if (null != chapters) {
            long  time=System.currentTimeMillis();

            //先判断最后一章的位置
            Map<String, String> lastChapter = get_last_chapter(book_id);
            int i = 0;
            if (lastChapter != null) {
                String lastUri = lastChapter.get(CHAPTERURI);
                for (i = chapters.size() - 1; i >= 0; i--) {

                    assert lastUri != null;
                    if (lastUri.equals(chapters.get(i).get(CHAPTERURI))) {
                        break;
                    }
                }
                i++;
            }

            ContentValues values = new ContentValues();
            Map<String, String> chapter;
            int addCount =0;
            Tab_Book.lock.lock();
            db.execSQL("begin;");
            for (; i < chapters.size(); i++) {
                values.clear();
                chapter = chapters.get(i);
                values.put(_ID, book_id);
                for (String field : fields) {
                    values.put(field, chapter.get(field));
                }
               long chapterID = db.insert(NAME, null, values);
                chapter.put(Tab_Chapter.CHAPTER_ID,String.valueOf(chapterID) );//添加成功有ID，赋值回去
                addCount++;
            }
            db.execSQL("commit;");
            Tab_Book.lock.unlock();
            if (Fun.isDebug()){
                time=System.currentTimeMillis()-time;
                Log.d("sql add chapter2", "add: time"+time);
            }
            return addCount;
        }
        return 0;
    }

    //获得所有章节
    public List<Map<String, String>> get_chapters(long book_id) {
        Cursor cursor = db.query(NAME, null, _ID + " = " + book_id,
                null, null, null, CHAPTER_ID + " ASC");
        List<Map<String, String>> chapters = new ArrayList<>();
        while (cursor.moveToNext()) {
            Map<String, String> chapter = new HashMap<>();
            for (int i = 0; i < fields.length; i++) {
                chapter.put(fields[i], cursor.getString(i + 2));
            }
            chapter.put(CHAPTER_ID, String.valueOf(cursor.getLong(1)));
            chapters.add(chapter);
        }
        cursor.close();
        return chapters;
    }

    public int getChapterCount(long book_id){
        Cursor cursor = db.rawQuery("select count(*) as count from "+NAME +
                " Where("+_ID + " = " + book_id+")",null);
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        cursor.close();
        return count;
    }

    public int getChapterIndex(long book_id, long chapter_id){
        Cursor cursor = db.query(NAME, new String[]{CHAPTER_ID}, _ID + " = " + book_id,
                null, null, null, CHAPTER_ID + " ASC");
        int ret =0;
        while (cursor.moveToNext()){
            long id = cursor.getLong(0);
            if (id==chapter_id){
                ret = cursor.getPosition();
                break;
            }

        }
        cursor.close();
        return ret;
    }

    public long getChapterIdFromIndex(long bookID,int index){
        Cursor cursor = db.query(NAME, new String[]{CHAPTER_ID}, _ID + " = " + bookID,
                null, null, null, CHAPTER_ID + " ASC");
        long ret =0;
        while (cursor.moveToNext()){
            long id = cursor.getLong(0);
            if (index==cursor.getPosition()){
                ret = id;
                break;
            }
        }
        cursor.close();
        return ret;
    }
    //获得最后添加的一章
    public Map<String, String> get_last_chapter(long book_id) {
        Cursor cursor = db.query(NAME, null, _ID + " = " + book_id,
                null, null, null, CHAPTER_ID + " DESC", " 1");
        Map<String, String> chapter = null;
        if (cursor.moveToNext()) {
            chapter = new HashMap<>();
            for (int i = 0; i < fields.length; i++) {
                chapter.put(fields[i], cursor.getString(i + 2));
            }
            chapter.put(CHAPTER_ID, String.valueOf(cursor.getLong(1)));
        }
        cursor.close();
        return chapter;
    }
}
